<template>
  <div class="common-layout">
    <el-container>
      <el-aside width="200px" style="height: 100vh;padding: 0;margin: 0;">
        <div class="question-nav">
          <div
              v-for="(question, index) in questionList"
              :key="index"
              :class="['nav-item', { 'current': index === currentQuestionIndex }]"
              @click="jumpToQuestion(index)"
          >
            {{ index + 1 }}
          </div>
        </div>
      </el-aside>
      <el-container>
        <!--header部分-->
        <el-header>
          <div class="header">
            <el-col :span="8" class="left-col">
              <!--测评卷标题-->
              <el-space>
                <el-icon>
                  <Document/>
                </el-icon>
                <h1 class="title">{{ paperInfo.title }}</h1>
              </el-space>
            </el-col>
            <!--进度条-->
            <el-col :span="8" class="center-col">
              <el-progress
                  :percentage="progressPercentage"
                  :color="progressColor"
              />
              <span>第 {{ currentQuestionIndex + 1 }} / {{ totalQuestions }} 题</span>
            </el-col>
            <!--倒计时-->
            <el-col :span="8" class="right-col">
              <el-countdown title="剩余时间" :value="timeLimit" v-if="paperInfo.timeLimit"/>
            </el-col>
          </div>
        </el-header>
        <el-main>
          <div class="card-container">
            <div class="cards-wrapper">
              <el-card
                  v-for="(question, index) in questionList"
                  :key="index"
                  class="card"
                  :style="getCardStyle(index)"
              >
                <!--题号和内容-->
                <div>
                  <h1>第{{ index + 1 }}题</h1>
                  <span><el-tag>{{ getQuestionTypeLabel(question.questionType) }}</el-tag></span>
                  <span><el-tag :type="question.required === '1'?'primary':'info'">{{
                      getRequiredLabel(question.required)
                    }}</el-tag></span>
                  <!--使用v-html渲染-->
                  <p style="font-size: 60px" v-html="question.content"></p>
                </div>
                <!--试题选项-->
                <!-- 答案区域 -->
                <div class="answer-area">
                  <!-- 单选题型 -->
                  <el-radio-group
                      v-if="question.questionType === '0'"
                      v-model="question.userAnswer"
                      class="options-container">
                    <el-radio
                        v-for="(opt, optIndex) in question.processedOptions"
                        :key="optIndex"
                        :value="opt.key"
                        class="option-item">
                      <span class="option-key">{{ opt.key }}.</span>
                      {{ getOptionLabel(opt.score) }}
                    </el-radio>
                  </el-radio-group>

                  <!-- 多选题型 -->
                  <el-checkbox-group
                      v-else-if="question.questionType === '1'"
                      v-model="question.userAnswer"
                      class="options-container">
                    <el-checkbox
                        v-for="(opt, optIndex) in question.processedOptions"
                        :key="optIndex"
                        :label="opt.key"
                        class="option-item">
                      <span class="option-key">{{ opt.key }}.</span>
                      {{ getOptionLabel(opt.score) }}
                    </el-checkbox>
                  </el-checkbox-group>

                  <!-- 填空题型 -->
                  <el-input
                      v-else-if="question.questionType === '2'"
                      v-model="question.userAnswer"
                      type="textarea"
                      placeholder="请输入答案"
                      :rows="3"/>
                </div>
                <div class="actions">
                  <el-button
                      class="question-button"
                      v-show="currentQuestionIndex !== 0"
                      @click="prev"
                  >
                    上一题
                  </el-button>
                  <el-button
                      class="question-button"
                      @click="next"
                  >
                    {{ currentQuestionIndex === questionList.length - 1 ? '确认' : '下一题' }}
                  </el-button>
                </div>
              </el-card>
            </div>
          </div>
        </el-main>
        <!--footer部分-->
        <el-footer class="el-footer">
          <div class="button-container">
            <el-row>
              <el-button type="success" @click="handleSubmit" v-show="submitFlag">提交试卷</el-button>
              <el-button type="info" @click="exitAssessment(paperId)">退出测评</el-button>
            </el-row>
          </div>
        </el-footer>
      </el-container>
    </el-container>
  </div>
</template>

<script setup lang="js">
import {computed, onMounted, reactive, ref} from "vue";
import {getPaperDetails} from "@/api/assessments/assessments.js";
import {Document} from "@element-plus/icons-vue";
import {addAnswer, resumeAssessment} from "@/api/answer/answer.js";
import {addRecord, checkRecord, saveCurrentRecord, submitPaper} from "@/api/record/record.js";

const {proxy} = getCurrentInstance();
const {question_type, exam_options, exam_required} = proxy.useDict('question_type', 'exam_options', 'exam_required');

const questionList = reactive([]);  // 题目列表
const currentQuestionIndex = ref(0);     // 当前题目索引
const totalQuestions = ref(0); // 总题目数
const paperId = ref();
const paperInfo = reactive({});
const timeLimit = ref(0);
const submitFlag = ref(false);
const tourFlag = ref(false);
const MIN_PERCENTAGE = 10;  // 最小百分比

// 退出测评
function exitAssessment(paperId) {
  console.log('退出测评', paperId)
  // 保存当前记录
  saveCurrentRecord(paperId);
  proxy.$router.push({path: '/online-assessments'})
}

// 处理提交测评
function handleSubmit() {
  const submission = questionList.map(q => ({
    questionId: q.id,
    type: q.questionType,
    userAnswer: q.userAnswer,
    required: q.required,
  }));
  // 判断是否还有未答题
  if (submission.some(q => q.required && !q.userAnswer)) {
    proxy.$modal.msgError('请完成所有必答题');
    return;
  }
  // 提交测评
  submitPaper(paperId.value).then(res => {
    if (res.code === 200) {
      proxy.$modal.msgSuccess(res.msg);
      // 1秒后跳转到success页面
      setTimeout(() => {
        proxy.$router.push({
          path: '/success',
          query: {  // 使用 query 传参
            paperId: paperId.value,
          }
        })
      }, 1000);
    } else {
      proxy.$modal.msgError(res.msg);
    }
  });
}

// 获取字典标签
const getDictLabel = (dictData, value) => {
  const target = dictData.find(item => item.value === value)
  return target ? target.label : '未知标签'
}

// 题型字典映射
function getQuestionTypeLabel(type) {
  return getDictLabel(question_type.value, type) || '未知题型';
}

// 是否必填字典映射
function getRequiredLabel(required) {
  return getDictLabel(exam_required.value, required.toString()) || '非必填';
}

// 字典选项值映射
const getOptionLabel = (score) => {
  return getDictLabel(exam_options.value, score.toString()) || '未知选项';
};

// 上一题
function prev() {
  if (currentQuestionIndex.value > 0) {
    console.log("上一题方法触发")
    currentQuestionIndex.value--;
  }
}

// 下一题
function next() {
  if (currentQuestionIndex.value === questionList.length - 1) {
    submitFlag.value = true;
  }
  if (currentQuestionIndex.value <= questionList.length - 1) {
    console.log("下一题方法触发")
    // 获取当前题目
    const currentQ = questionList[currentQuestionIndex.value];
    // 转换答案值为实际数值
    let answerValue = '';
    if (currentQ.questionType === '0') { // 单选题
      const selectedOption = currentQ.processedOptions.find(
          opt => opt.key === currentQ.userAnswer
      );
      answerValue = selectedOption ? selectedOption.score : '';
    } else if (currentQ.questionType === '1') { // 多选题
      answerValue = currentQ.userAnswer.map(key => {
        const option = currentQ.processedOptions.find(opt => opt.key === key);
        return option ? option.score : null;
      }).filter(score => score !== null).join(',');
    } else { // 填空题
      answerValue = currentQ.userAnswer;
    }

    // 构造提交数据
    const data = {
      paperId: paperId.value,
      questionId: currentQ.id, // 使用题目真实ID
      answer: currentQ.userAnswer,
      score: answerValue,
    };
    addAnswer(data).then(response => {
      if (response.code === 200) {
        if (currentQuestionIndex.value < questionList.length - 1) {
          // 切换到下一个卡片
          currentQuestionIndex.value++;
        }
      }
    });
  }
}

// 动态卡片样式
const getCardStyle = (index) => {
  if (index === currentQuestionIndex.value) {
    return {
      transform: "translateX(0)",
      zIndex: 2,
      opacity: 1
    };
  }
  return {
    transform: `translateX(${index < currentQuestionIndex.value ? "-100%" : "100%"})`,
    zIndex: 1,
    opacity: 0
  };
};

// 获取试卷和试题信息
const initPaperDetails = (paperId) => {
  return getPaperDetails(paperId).then(res => {
    Object.assign(paperInfo, res.data.examPaper);
    questionList.push(...res.data.examQuestions.map(q => {
      // 解析选项并处理数据
      let processedOptions = [];
      try {
        processedOptions = JSON.parse(q.options).map(opt => ({
          ...opt,
          // 转换score为数字类型
          score: Number(opt.score)
        }));
      } catch (e) {
        console.error('选项解析失败:', q.options);
      }

      return {
        ...q,
        processedOptions,
        // 根据题型初始化答案存储结构
        userAnswer: q.questionType === '1' ? [] : '' // 多选初始化为数组
      };
    }));

    totalQuestions.value = questionList.length;
  });
};

// 确认框
function confirm() {
  // 添加空值校验
  if (!paperInfo.title) {
    proxy.$modal.msgError("试卷信息加载失败")
    return
  }

  proxy.$confirm(`是否开始${paperInfo.title}测评？`, '提示', {
    confirmButtonText: '开始测评',
    cancelButtonText: '返回',
    type: 'warning',
    showClose: false,
    closeOnClickModal: false, // 添加防止误关闭
    closeOnPressEscape: false
  }).then(() => {
    console.log('开始测评流程触发')
    tourFlag.value = true
    addRecord(paperId.value).then(() => {
      timeLimit.value = Date.now() + paperInfo.timeLimit * 60 * 1000
      checkTimeLimit()
    }).catch(err => {
      proxy.$modal.msgError("初始化失败，请重试")
    })
  }).catch(() => {
    proxy.$router.push({path: '/online-assessments'})
  })
}

// 倒计时校验
function checkTimeLimit() {
  // 如果是不限制时间
  if (paperInfo.timeLimit === null) {
    return;
  }
  // 设置定时器检查倒计时
  let countdownInterval = setInterval(() => {
    if (Date.now() >= timeLimit.value) {
      console.log('结束测评');
      clearInterval(countdownInterval);
      // 可以在这里添加其他结束测评的操作，比如跳转页面或提示用户
    }
  }, 1000); // 每秒检查一次
}

// 进度条
// 计算进度百分比（保留整数）
const progressPercentage = computed(() => {
  if (totalQuestions.value === 0) {
    return 0; // 防止除以0
  }
  if (currentQuestionIndex.value === 0 && totalQuestions.value !== 1) {
    return MIN_PERCENTAGE; // 第一题时显示最小百分比
  }
  if (currentQuestionIndex.value === totalQuestions.value - 1) {
    return 100; // 最后一题时显示100%
  }
  // 线性插值计算进度百分比
  const basePercentage = (currentQuestionIndex.value / (totalQuestions.value - 1)) * 100;
  return Math.round(basePercentage);
});
// 动态进度条颜色
const progressColor = computed(() => {
  return progressPercentage.value === 100 ? '#67c23a' : '#409eff';//
});

// 左侧Aside跳转到指定题目
const jumpToQuestion = (index) => {
  if (index >= 0 && index < questionList.length) {
    currentQuestionIndex.value = index;
  }
};

// 前置校验
function perCheck() {
  checkRecord(paperId.value).then(response => {
    console.log("前置校验：", response)
    if (response.data && (response.data.status === '0' || response.data.status === '2')) {
      // 说明有未完成的测评
      proxy.$confirm(`您有未完成的测评，是否继续上次测评？`, '提示', {
        confirmButtonText: '继续测评',
        cancelButtonText: '退出测评',
        type: 'warning',
        showClose: false,
      }).then(() => {
        console.log('继续测评');
        // 在 resumeAssessment 的回调中处理
        resumeAssessment(paperId.value).then(response => {
          console.log("继续测评：", response)
          initPaperDetails(paperId.value).then(() => {
            // 恢复进度
            restoreProgress(response.data.answerList);
            confirm();
          });
        })
      }).catch(() => {
        // 点击退出测评
        console.log('退出测评！')
        proxy.$router.push({path: '/online-assessments'})
      })
    } else if (response.code === 200) {
      console.log("初次测评！")
      initPaperDetails(paperId.value).then(() => {
        confirm();
      }).catch(error => {
        console.error("初始化测评卷数据失败", error);
      });
    } else {
      alert("该测评已完成")
      proxy.$router.push({path: '/online-assessments'})
    }
  })
}

// 恢复答题进度
const restoreProgress = (progressData) => {
  progressData.forEach((item, index) => {
    if (index >= questionList.length) {
      return;
    }
    try {
      const answerObj = JSON.parse(item);
      const keys = Object.keys(answerObj).filter(k => k); // 过滤空key
      // 根据题型处理答案
      switch (questionList[index].questionType) {
        case '0': // 单选
          questionList[index].userAnswer = keys[0] || '';
          break;
        case '1': // 多选
          questionList[index].userAnswer = keys;
          break;
        case '2': // 填空
          questionList[index].userAnswer = answerObj[keys[0]]?.toString() || '';
          break;
      }
    } catch (e) {
      console.error(`第${index + 1}题进度解析失败`, e);
    }
  });
  // 定位到最新题目
  locateLatestQuestion(progressData);
};
// 定位到最新进度
const locateLatestQuestion = (progressData) => {
  // 找到最后一个有效答题的索引
  let lastAnsweredIndex = -1;

  progressData.forEach((item, index) => {
    try {
      const answerObj = JSON.parse(item);
      if (Object.values(answerObj).some(v => v !== null)) {
        lastAnsweredIndex = index;
      }
    } catch (e) {
      console.error(`进度解析错误`, e);
    }
  });

  // 设置当前题目索引（最后一个已回答的下一个或末尾）
  currentQuestionIndex.value = Math.min(
      lastAnsweredIndex + 1,
      questionList.length - 1
  );

  // 如果全部已回答但未提交，显示确认按钮
  submitFlag.value = (lastAnsweredIndex === questionList.length - 1);
};

// 生命周期函数
onMounted(() => {
  // 获取路由传递的参数
  paperId.value = proxy.$route.query.paperId;
  // 前置校验
  perCheck();
})
</script>

<style scoped>
.options-container {
  display: flex;
  flex-direction: column; /* 垂直排列 */
  gap: 12px;
  width: 100%;
}

/* 强制每个选项占满整行 */
:deep(.el-radio),
:deep(.el-checkbox) {
  display: flex;
  width: 100%;
  align-items: center;
  margin: 0;
}

/* 调整Element组件内部布局 */
:deep(.el-radio__label),
:deep(.el-checkbox__label) {
  display: flex;
  align-items: center;
  width: calc(100% - 20px); /* 留出前面选框的位置 */
}

.option-item {
  width: 100%;
  height: 40px;
  padding: 8px 12px;
  border-radius: 4px;
  border: 1px solid var(--el-border-color);
  transition: all 0.3s;
}

.option-item:hover {
  border-color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);
}

.option-key {
  min-width: 24px;
  font-weight: 500;
  color: var(--el-color-primary);
}

/* 底部样式 */
.el-footer {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 50px;
}

.button-container {
  display: flex;
  gap: 90px; /* 按钮之间的间距 */
}

/* 题目导航组件样式 */
.question-nav {
  padding: 20px;
  display: flex;
  flex-wrap: wrap; /* 允许换行 */
  gap: 10px; /* 元素间距 */
}

.nav-item {
  width: 30px;
  height: 30px;
  line-height: 30px;
  border-radius: 50%;
  background: #f0f0f0;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
}

.nav-item:hover {
  background: #e0e0e0;
}

.nav-item.current {
  background: #67c23a; /* 绿色高亮 */
  color: white;
}


/* 头部样式 */
.header {
  display: flex;
  justify-content: space-between; /* 关键：三列等分并贴边 */
  align-items: center;
  padding: 0 20px;
  height: 80px;
  background-color: #f5f5f5;
  border-bottom: 1px solid #e0e0e0;
}

/* 标题强制左对齐 */
.left-col {
  display: flex;
  justify-content: flex-start; /* 内容左对齐 */
}

/* 倒计时右对齐 */
.right-col {
  display: flex;
  justify-content: flex-end; /* 内容右对齐 */
}

/* 确保倒计时组件右对齐 */
.countdown-wrapper {
  display: flex;
  justify-content: flex-end;
  width: 100%;
}

.card-container {
  position: relative;
  width: 100%;
  height: 950px; /* 根据实际需要调整高度 */
  overflow: hidden;
}

.cards-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
}

.card {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1);
}

.actions {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
}

/* 优化按钮样式 */
.question-button {
  padding: 12px 24px;
}

.question-button:hover {
  background-color: #f3fdf3;
}
</style>

